package web.eshop.wizard;


import application.MySession;
import org.apache.wicket.extensions.wizard.Wizard;
import org.apache.wicket.extensions.wizard.WizardModel;
import org.apache.wicket.extensions.wizard.WizardStep;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RadioChoice;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.customer.ShopCustomerService;
import web.eshop.MultipleProductsEshopPage;
import web.eshop.order.OrderPage;
import web.eshop.wizard.RegWizardThirdStep.ThirdStepResultSet;

import java.util.List;
import java.util.Map;

public class RegisteredWizard extends Wizard {

    @SpringBean
    private ShopCustomerService shopCustomerService;
    @SpringBean
    private MySession mySession;
    private RegWizardModel regWizardModel;
    private RegWizardThirdStep regWizardThirdStep;

    public RegisteredWizard(String id) {
        super(id);
        regWizardModel = new RegWizardModel();
        setDefaultModel(new CompoundPropertyModel(regWizardModel));
        WizardModel model = new WizardModel();

        model.add(new RegWizardFirstStep());
        model.add(new RegWizardSecondStep(regWizardModel));
        regWizardThirdStep = new RegWizardThirdStep(regWizardModel);
        model.add(regWizardThirdStep);
        init(model);
    }

    /**
     * In this step customer choose from which car type want to see products.
     */
    private final class RegWizardFirstStep extends WizardStep {

        private Form mainForm = new Form("mainForm");
        private List<String> carTypeStringList;

        private RegWizardFirstStep() {
            carTypeStringList = shopCustomerService.getAllVehicleTypes();
            RadioChoice rc = new RadioChoice("choicedCarType",
                    carTypeStringList);
            rc.setRequired(true);
            mainForm.add(rc);
            add(mainForm);
        }
    }

    /**
     * Add selected components into order.
     */
    @Override
    public void onFinish() {
        ThirdStepResultSet thirdStepResultSet = regWizardThirdStep.getThirdStepResultSet();
        List<Long> componentsIds = thirdStepResultSet.getSelectedProductsIds();
        Map<Long, Integer> multiplicityMap = thirdStepResultSet.getMultiplicityMap();
        for (Long productId : componentsIds) {
            shopCustomerService.addProductToBasket(productId, multiplicityMap.get(productId));
        }
        setResponsePage(OrderPage.class);
    }

    @Override
    public void onCancel() {
        setResponsePage(MultipleProductsEshopPage.class);
    }
}
